// INCLUDE FILES
#include <eikenv.h>
#include <coemain.h>
#include <e32std.h>
#include <msvids.h>
#include <msvstd.h>
#include <smsclnt.h>
#include <smut.h>
#include <mtclreg.h>
#include <txtrich.h>
#include <smscmds.h>
#include <mtmuibas.h>
#include <mtmdef.h>
#include <stringloader.h>
#include "SmsHandler.h"
#include "smutset.h"
#include "smuthdr.h"
#include <aknnotewrappers.h>



// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CSmsHandler::CSmsHandler()
// C++ default constructor can NOT contain any code, that might leave.
// -----------------------------------------------------------------------------
//
CSmsHandler::CSmsHandler()
    {
    iNextUnread = 0;            // index of next unread message in iSelection
    }

// -----------------------------------------------------------------------------
// CSmsHandler::ConstructL()
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CSmsHandler::ConstructL()
    {
 // Session to message server is opened synchronously.
    iSession = CMsvSession::OpenSyncL( *this );

    iMtmRegistry = CClientMtmRegistry::NewL(*iSession);
    //iMtm = iMtmRegistry->NewMtmL(KUidMsgTypeSMS);
    iSmsMtm = STATIC_CAST(CSmsClientMtm*,iMtmRegistry->NewMtmL(KUidMsgTypeSMS));
    
    // Entry selection for all received messages.
    iSelection = new ( ELeave ) CMsvEntrySelection();
    //iMtmRegistry = CClientMtmRegistry::NewL( *iSession );

        // Create an SMS Client MTM object.
        //iSmsMtm = STATIC_CAST( CSmsClientMtm*, iMtmRegistry->NewMtmL( KUidMsgTypeSMS ) );
    }

// -----------------------------------------------------------------------------
// CSmsHandler::NewL()
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CSmsHandler* CSmsHandler::NewL( )
    {
    CSmsHandler* self = NewLC( );
    CleanupStack::Pop( self );
    return self;
    }

// -----------------------------------------------------------------------------
// CSmsHandler::NewLC()
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CSmsHandler* CSmsHandler::NewLC()
    {
    CSmsHandler* self = new ( ELeave ) CSmsHandler();
    CleanupStack::PushL( self );
    self->ConstructL();
    return self;
    }

// ----------------------------------------------------------
// CSmsHandler::~CSmsHandler()
// Destructor.
// ----------------------------------------------------------
//
CSmsHandler::~CSmsHandler()
    {
    delete iOperation;
    delete iMtmUiRegistry;
    delete iSelection;
	delete iSmsMtm;
    delete iMtmRegistry;
    delete iSession;    // session must be deleted last
    }

// -----------------------------------------------------------------------------
// CSmsHandler::DoCancel()
// Cancels a request.
// -----------------------------------------------------------------------------
//
void CSmsHandler::DoCancel()
    {
    if ( iOperation )
        {
        iOperation->Cancel();
        }
    }


// -----------------------------------------------------------------------------
// CSmsHandler::HandleSessionEventL()
// Handles notifications of events from the Message Server.
// -----------------------------------------------------------------------------
//
void CSmsHandler::HandleSessionEventL( TMsvSessionEvent aEvent,
                                      TAny* aArg1, TAny* aArg2, TAny* /*aArg3*/)
	{
	switch ( aEvent )
		{
        // Session to server established
		case EMsvServerReady:
            {
            TMsvId serviceId( KUidMsgTypeSMS.iUid ); // SMS service id

            // Determine if the event was succesful.
            // ServiceProgress inserts TBuf8 value in progress.
            TBuf8<KBfrLength> progress;
			iSession->ServiceProgress( serviceId, progress );
			_LIT8( KCompare, "KErrNone" );

			if ( progress.Compare( KCompare ) )
				{
                // Check that MtmRegistry has not already been accessed.
                if ( !iMtmRegistry )
                    {
                    AccessMtmL();
                    }
                }
            break;
            }

        // A new entry has been created on the message server.
        case EMsvEntriesCreated:
            {
            // Entry id is obtained from the session event arguments.
			   break;
            }
        case EMsvCloseSession:
        case EMsvServerTerminated:
        case EMsvGeneralError:
        case EMsvServerFailedToStart:
            {
//            iSmsAppUi->ServerDown( aEvent );    // close application
            break;
            }

        // All other events are ignored.
        default:
            break;
        }
    }

// -----------------------------------------------------------------------------
// CSmsHandler::AccessMtmL()
// Access the MTM Registry and create a SMS specific Client MTM instance.
// -----------------------------------------------------------------------------
//
void CSmsHandler::AccessMtmL()
	{
    // Create an MTM Registry object.
    
    }

// -----------------------------------------------------------------------------
// CSmsHandler::SendL()
// Starts the process of creating and sending an SMS message.
// -----------------------------------------------------------------------------
//
TBool CSmsHandler::SendL( const TDesC& aRecipientNumber,
                            const TDesC& aMessageText )
    {
    iRecipientNumber = aRecipientNumber;
    iMessageText = aMessageText;

    if ( CreateMsgL() )
        {
        return ETrue;
        }

    return EFalse;
    }

// -----------------------------------------------------------------------------
// CSmsHandler::CreateMsgL()
// Create an SMS message.
// -----------------------------------------------------------------------------
//
TBool CSmsHandler::CreateMsgL()
    {
    // Current entry is the Draft folder.
    iSmsMtm->SwitchCurrentEntryL( KMsvDraftEntryId );

    // Create a new SMS message entry as a child of the current context.
    iSmsMtm->CreateMessageL( KUidMsgTypeSMS.iUid );

    CMsvEntry& serverEntry = iSmsMtm->Entry();
    TMsvEntry entry( serverEntry.Entry() );

    CRichText& body = iSmsMtm->Body();   // the body of the message
    body.Reset();
    // Insert the message text gotten as input from user.
    body.InsertL( 0, iMessageText );

    // Message will be sent immediately.
    entry.SetSendingState( KMsvSendStateWaiting );

//Added by Kiran:for 3rd edition
//    entry.iDate.HomeTime(); // insert current time //This was causing problem:SMS stays into Outbox only.
	entry.iDate.UniversalTime(); // insert current time //Solution for HomeTime()
//Code Ends-Kiran
    // Set the SMS message settings for the message.
    CSmsHeader& header = iSmsMtm->SmsHeader();
    CSmsSettings* settings = CSmsSettings::NewL();
    CleanupStack::PushL( settings );

    settings->CopyL( iSmsMtm->ServiceSettings() );    // restore settings
    settings->SetDelivery( ESmsDeliveryImmediately ); // to be delivered immediately
	settings->SetDeliveryReport(ETrue);
    header.SetSmsSettingsL( *settings );              // new settings

	// Let's check if there is a service center address.
	if ( header.Message().ServiceCenterAddress().Length() == 0 )
		{
		// No, there isn't. We assume there is at least one service center
        // number set and use the default service center number.
		CSmsSettings* serviceSettings = &( iSmsMtm->ServiceSettings() );

        // Check if number of service center addresses in the list is null.

//Changed for 3rd Edition specially- Kiran - 30-10-06
//        if ( !serviceSettings->NumSCAddresses() )
		if ( !serviceSettings->ServiceCenterCount() )
            {
			return EFalse;     // quit creating the message
            }

		else
			{
//Changed for 3rd Edition specially- Kiran - 30-10-06
//          CSmsNumber* smsCenter = &( serviceSettings->SCAddress( serviceSettings->DefaultSC() ) );
				CSmsNumber* smsCenter= CSmsNumber::NewL();
				CleanupStack::PushL(smsCenter);
				smsCenter->SetAddressL((serviceSettings->GetServiceCenter( serviceSettings->DefaultServiceCenter())).Address());
				header.Message().SetServiceCenterAddressL( smsCenter->Address() );
				CleanupStack::PopAndDestroy(smsCenter);
		    }
        }

	CleanupStack::PopAndDestroy( settings );

    // Recipient number is displayed also as the recipient alias.
    entry.iDetails.Set( iRecipientNumber );
    // Add addressee.
    iSmsMtm->AddAddresseeL( iRecipientNumber, entry.iDetails );

    // Validate message.
    if ( !ValidateL() )
        {
        return EFalse;
        }

    entry.SetVisible( ETrue );          // set message as visible
    entry.SetInPreparation( EFalse );   // set together with the visibility flag
    serverEntry.ChangeL( entry );       // commit changes		
    iSmsMtm->SaveMessageL();            // save message

    TMsvSelectionOrdering selection;
	CMsvEntry* parentEntry = CMsvEntry::NewL( iSmsMtm->Session(), KMsvDraftEntryId, selection );
    CleanupStack::PushL( parentEntry );

    // Move message to Outbox.

    CleanupStack::PopAndDestroy( parentEntry );

    iState = EWaitingForMoving;

    return ETrue;
  }

TDesC CSmsHandler::GetServiceCenterNumber()
	{
	CSmsHeader& header = iSmsMtm->SmsHeader();
	CSmsSettings* settings = CSmsSettings::NewL();
	CleanupStack::PushL(settings);

	settings->CopyL(iSmsMtm->ServiceSettings()); // restore settings
	settings->SetDelivery(ESmsDeliveryImmediately); // to be delivered immediately
	settings->SetDeliveryReport(ETrue);
	header.SetSmsSettingsL(*settings); // new settings

	// Let's check if there is a service center address.
	if (header.Message().ServiceCenterAddress().Length() == 0)
		{
		// No, there isn't. We assume there is at least one service center
		// number set and use the default service center number.
		CSmsSettings* serviceSettings = &(iSmsMtm->ServiceSettings());

		// Check if number of service center addresses in the list is null.

		//Changed for 3rd Edition specially- Kiran - 30-10-06
		//        if ( !serviceSettings->NumSCAddresses() )
		
		if (!serviceSettings->ServiceCenterCount())
			{
			//return _L(""); // quit creating the message
			//centerNumber.Cop
			}

		else
			{
			//Changed for 3rd Edition specially- Kiran - 30-10-06
			//          CSmsNumber* smsCenter = &( serviceSettings->SCAddress( serviceSettings->DefaultSC() ) );
			CSmsNumber* smsCenter = CSmsNumber::NewL();
			CleanupStack::PushL(smsCenter);
			return serviceSettings->GetServiceCenter(serviceSettings->DefaultServiceCenter()).Address();
		
			}
		}
		return _L("");
	}

// -----------------------------------------------------------------------------
// CSmsHandler::ValidateL()
// Validate an SMS message.
// -----------------------------------------------------------------------------
//
TBool CSmsHandler::ValidateL()
    {
    // Empty part list to hold the result.
    TMsvPartList result( KMsvMessagePartNone );

    // Validate message body.
    result = iSmsMtm->ValidateMessage( KMsvMessagePartBody );

    if ( result != KMsvMessagePartNone )
        {
        return EFalse;
        }

    // Validate recipient.
    result = iSmsMtm->ValidateMessage( KMsvMessagePartRecipient );

    if ( result != KMsvMessagePartNone )
        {
        return EFalse;
        }

    return ETrue;
    }

// -----------------------------------------------------------------------------
// CSmsHandler::ScheduleL()
// Schedule an SMS message for sending.
// -----------------------------------------------------------------------------
//
void CSmsHandler::ScheduleL()
    {
    }

// -----------------------------------------------------------------------------
// CSmsHandler::MessageReceivedL()
// Handles a received SMS message.
// -----------------------------------------------------------------------------
//
void CSmsHandler::MessageReceivedL( TMsvId aEntryId )
    {
   
    }

void CSmsHandler::CreateLocalSMS(const TDesC& aRecipientNumber,
        const TDesC& aMessageText)
	{
		/*TBuf<10> aAddress(_L("Nokia"));
		TBuf<20> aDescription(_L("Important Message"));
	 
		_LIT(KTxt1,"Hi phone owner, how r u?");*/
	 
		/*TBuf<150> iMessage;	
		iMessage.Copy(KTxt1);*/
	 
		//iMtmRegistry = CClientMtmRegistry::NewL(*iSession);
	  	//iSmsMtm = STATIC_CAST( CSmsClientMtm*,  iMtmRegistry->NewMtmL(KUidMsgTypeSMS));
	 
	  	iSmsMtm->SwitchCurrentEntryL(KMsvGlobalInBoxIndexEntryId); //inbox
	 
	  	iSmsMtm->CreateMessageL(KUidMsgTypeSMS.iUid);
	 
	  	CSmsHeader& iHeader = iSmsMtm->SmsHeader();
	  	iHeader.SetFromAddressL(aRecipientNumber);
	 
	 
	  	CRichText& body = iSmsMtm->Body();
	  	body.Reset();
	  	body.InsertL(0, aMessageText);
	 
	  	TMsvEntry entry = iSmsMtm->Entry().Entry();
	  	entry.SetInPreparation(EFalse);
	  	entry.SetVisible(ETrue);
	  	entry.iDate.HomeTime();
	  	//entry.iDescription.Set(aDescription);
	  	entry.iDetails.Set(aRecipientNumber);
	  	entry.SetUnread(ETrue);
	 
	 
	  	iSmsMtm->Entry().ChangeL(entry);
	  	iSmsMtm->SaveMessageL();
	}

